<?php

namespace common\models\search;


use common\models\User;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use Yii;
use yii\rbac\DbManager;
use yii\validators\DateValidator;

class UserSearch extends Model
{
    public $id;

    public $username;

    public $email;

    public $status;

    public $role;

    public $created_at;

    public $last_login;

    public function rules()
    {
        return [
            [['id', 'username', 'email', 'status', 'role', 'last_login', 'created_at'], 'safe'],
        ];
    }

    /**
     * @param $params
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = User::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => ['id' => SORT_DESC],
            ]
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere(['id' => $this->id]);
        $query->andFilterWhere(['like', 'username', $this->username]);
        $query->andFilterWhere(['like', 'email', $this->email]);
        $query->andFilterWhere(['status' => $this->status]);

        if ($this->role) {
            $authManager = Yii::$app->getAuthManager();
            if ($authManager instanceof DbManager) {
                $query->join('INNER JOIN', $authManager->assignmentTable . ' auth', 'auth.user_id = id');
                $query->andFilterWhere(['auth.item_name' => $this->role]);
            }
        }

        foreach (['last_login', 'created_at'] as $attribute) {
            if ($this->$attribute !== '') {
                $parts = array_map('trim', explode('/', $this->$attribute));
                if (count($parts) == 2) {
                    if ($parts[0] === $parts[1]) {
                        if ($parts[0] === date('Y-m-d')) {
                            $parts[1] .= ' ' . date('H:i:s');
                        }
                        if ($parts[0] == date('Y-m-d', strtotime('yesterday'))) {
                            $parts[1] = date('Y-m-d');
                        }
                    }

                    $query->andFilterWhere(['between', $attribute, strtotime($parts[0]), strtotime($parts[1])]);
                } else {
                    $query->andFilterWhere([$attribute => $this->$attribute]);
                }
            }
        }

        return $dataProvider;
    }
} 